package com.huawei.appmessage.codelab;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;

import com.huawei.agconnect.appmessaging.AGConnectAppMessaging;
import com.huawei.agconnect.appmessaging.AGConnectAppMessagingCallback;
import com.huawei.agconnect.appmessaging.AGConnectAppMessagingOnClickListener;
import com.huawei.agconnect.appmessaging.AGConnectAppMessagingOnDismissListener;
import com.huawei.agconnect.appmessaging.AGConnectAppMessagingOnDisplayListener;
import com.huawei.agconnect.appmessaging.model.AppMessage;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.agconnect.remoteconfig.ConfigValues;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.aaid.entity.AAIDResult;
import com.huawei.hms.analytics.HiAnalytics;
import com.huawei.hms.analytics.HiAnalyticsInstance;

import java.util.Map;
import com.bumptech.glide.*;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "AppMessaging";
    private AGConnectAppMessaging appMessaging;
    private Button addView;
    private Button rmView;
    private TextView textView;
    private  ImageView imageView;

    Map<String, Object> mapRemoteCofig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addView = findViewById(R.id.add_custum_view);
        rmView = findViewById(R.id.remove_custum_view);
        textView = findViewById(R.id.textview);
        imageView = findViewById(R.id.imageView);

        //get your device's aaid for testing asynchronously
        HmsInstanceId inst  = HmsInstanceId.getInstance(this);
        Task<AAIDResult> idResult =  inst.getAAID();
        idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
            @Override
            public void onSuccess(AAIDResult aaidResult) {
                String aaid = aaidResult.getId();
                textView.setText(aaid);
                Log.d(TAG, "getAAID success:" + aaid );

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.d(TAG, "getAAID failure:" + e);
            }
        });

        appMessaging = AGConnectAppMessaging.getInstance();
        appMessaging.setFetchMessageEnable(true);
        appMessaging.setDisplayEnable(true);


        // setForceFetch for testing
        AGConnectAppMessaging.getInstance().setForceFetch();
        appMessaging.addOnDisplayListener(new AGConnectAppMessagingOnDisplayListener() {
            @Override
            public void onMessageDisplay(AppMessage appMessage) {
                Toast.makeText(MainActivity.this, "Message showed", Toast.LENGTH_LONG).show();
            }
        });
        appMessaging.addOnClickListener(new AGConnectAppMessagingOnClickListener() {
            @Override
            public void onMessageClick(AppMessage appMessage) {
                Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_LONG).show();
            }
        });
        appMessaging.addOnDismissListener(new AGConnectAppMessagingOnDismissListener() {
            @Override
            public void onMessageDismiss(AppMessage appMessage, AGConnectAppMessagingCallback.DismissType dismissType) {
                Toast.makeText(MainActivity.this, "Message Dismiss, dismiss type: " + dismissType, Toast.LENGTH_LONG).show();
            }
        });

        // apply custom view
        addView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomView customView = new CustomView(MainActivity.this);
                appMessaging.addCustomView(customView);
            }
        });

        // restore initial view
        rmView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                appMessaging.removeCustomView();
            }
        });

        getRemoteConifg();
    }

    private void getRemoteConifg() {
        final AGConnectConfig config= AGConnectConfig.getInstance();

        final SharedPreferences preferences = this.getApplicationContext().getSharedPreferences("Remote_Config", MODE_PRIVATE);
        long fetchInterval =6;// 12 * 60 * 60L;
        if (preferences.getBoolean("DATA_OLD", false)) {
            fetchInterval = 0;
        }

        config.fetch(fetchInterval).addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
            @Override
            public void onSuccess(ConfigValues configValues) {
                try {
                    config.apply(configValues);
                    showAllValues(config);
                    preferences.edit().putBoolean("DATA_OLD", false).apply();
                    Toast.makeText(getBaseContext(), "Fetch Success", Toast.LENGTH_LONG).show();


                    int localVer = getversioncode();
                    String strReVer = (String) mapRemoteCofig.get("lowVer");
                    int iReVer = Integer.valueOf(strReVer).intValue();
                    if(localVer < iReVer){

                        Toast.makeText(getBaseContext(), "版本低，需升级", Toast.LENGTH_LONG).show();
                        trigUpdateMsg();
                    }

                    String strImg=(String) mapRemoteCofig.get("imgsrc");
                    changeImg(strImg);

                }catch (Exception ex){
                    ex.printStackTrace();
                }

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Toast.makeText(getBaseContext(), "Fetch Fail", Toast.LENGTH_LONG).show();
            }
        });
    }
//使用配置值

    
    private void changeImg(String strImg) {
        Glide.with(this).load(strImg).into(imageView);
    }

    private void trigUpdateMsg(){

//        AccessNetworkManager.setAccessNetwork(true);


        Bundle bundle = new Bundle();
        Context context = getApplicationContext();

        HiAnalyticsInstance instance = HiAnalytics.getInstance(context);
//        HiAnalyticsTools.enableLog();

        instance.onEvent("$Search", bundle);
    }


    private void showAllValues(AGConnectConfig config) {
        // Merge the default parameters and the parameters fetched from the cloud
       mapRemoteCofig = config.getMergedAll();

        StringBuilder string = new StringBuilder();
        for (Map.Entry<String, Object> entry : mapRemoteCofig.entrySet()) {
            string.append(entry.getKey());
            string.append(" : ");
            string.append(entry.getValue());
            string.append("\n");
        }


        Toast.makeText(getBaseContext(), string, Toast.LENGTH_LONG).show();
        System.out.println(string);

    }


    private int getversioncode() throws Exception {

// 获取packagemanager的实例

        PackageManager  packagemanager =getPackageManager();

// getpackagename()是你当前类的包名，0代表是获取版本信息

        PackageInfo packinfo = packagemanager.getPackageInfo(getPackageName(), 0);

        int version = packinfo.versionCode;

        return version;

    }
}
